<?php
declare(strict_types=1);

namespace LowCode\Traits\Vue;

use Illuminate\Support\Collection;

trait HasReactive
{
    /**
     * @param string $reactiveKey
     * @param array $reactiveValue
     * @return $this
     */
    public function reactive(string $reactiveKey, array $reactiveValue = []): static
    {
        $reactiveValue = json_encode($reactiveValue, JSON_UNESCAPED_UNICODE);
        $this->builder->reactive->put($reactiveKey, "const $reactiveKey = reactive($reactiveValue)");
        $this->variables->add($reactiveKey);
        return $this;
    }

    /**
     * @param string $reactiveKey
     * @return $this
     */
    public function removeReactive(string $reactiveKey): static
    {
        if ($this->builder->reactive->has($reactiveKey)){
            $this->builder->reactive->forget($reactiveKey);
            $variables = $this->variables->forget($reactiveKey)->values()->all();
            $this->variables = Collection::make($variables);
        }
        return $this;
    }

    protected function getReactiveHtml(): string
    {
        $this->reactive("state",$this->state);
        if ($this->builder->reactive->isNotEmpty()){
            $this->addVueImport("reactive");
        }
        $values = $this->builder->reactive->all();
        return $this->implode($values);
    }
}
